package com.ghck.server.aop;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ghck.server.exception.ErrorConstant;
import com.ghck.server.model.Users;
import com.ghck.server.model.response.Result;


@Aspect
public class ApiAccessAspect {
	private static Logger LOGGER = LoggerFactory.getLogger(ApiAccessAspect.class);
	
	private String requireLoginString = "未登录，或登录已过期，请重新登录";
	
	public static final String P_CALLBACK = "callback";
	
	@Pointcut("execution(* com.ghck.server.bkcontroller..*Controller.*(..))")
	private void pointCutMethod() {}
	
	@Around(value="pointCutMethod()")
	public Object around(ProceedingJoinPoint pjp) throws Throwable{
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
		Timestamp reqPointTime = new Timestamp(System.currentTimeMillis());
		MethodSignature joinPointObject = (MethodSignature) pjp.getSignature(); //获取拦截方法
		RequestMapping requestMapping = joinPointObject.getMethod().getAnnotation(RequestMapping.class);
		PathAndMsgOnError pathAndMsgOnError = joinPointObject.getMethod().getAnnotation(PathAndMsgOnError.class);
		RequireLogin requireLogin = joinPointObject.getMethod().getAnnotation(RequireLogin.class);
		ResponseBody responseBody = joinPointObject.getMethod().getAnnotation(ResponseBody.class);
		String url = request.getRequestURI().toLowerCase();
		Class[] parameterTypes = joinPointObject.getParameterTypes();
		request.setAttribute("currentUrl", url);
		Object[] args = pjp.getArgs();
		RedirectAttributes redirectAttributes = null;
		for(Object arg : args){
			/**
			if(null != arg){
				Class<?> c = null;
				String className = arg.getClass().getName();
				LOGGER.info("className {}",className);
				if(className.startsWith("com.ghck")){
					Field[] declaredFields = arg.getClass().getDeclaredFields();
			        for (int i = 0; i < declaredFields.length; i++) {
			        	Field field = declaredFields[i];
			        	Class<?> type = field.getType();
			        	LOGGER.info("type : {}",type);
			        	//得到修饰符的数字
			            int modifiers = declaredFields[i].getModifiers();
			            System.out.println(modifiers);
			            LOGGER.info("modifiers : {}",modifiers);
			            if(modifiers  != 26){  // private static final
			            	Object value = field.get(field.getName());
			            	LOGGER.info("value : {}",value);
			            }
			            //取得属性的修饰符
//			            String priv = Modifier.toString(modifiers);
//			            LOGGER.info("priv : {}",priv);
			        	
			        }
				}
				request.setAttribute(name, o);
			}
			*/
			if(arg!=null && RedirectAttributes.class.isAssignableFrom(arg.getClass())){
				redirectAttributes = (RedirectAttributes) arg;
			}
		}
		try{
			if(requireLogin!=null){
				HttpSession session = request.getSession();
				Users su = (Users) session.getAttribute("user");
				if(su==null){
					if(redirectAttributes!=null){
						redirectAttributes.addFlashAttribute(pathAndMsgOnError.errorMsgField(), requireLoginString);
					}
					
					request.setAttribute("errorMsg", requireLoginString);
					return "login";
				}
			}
			
		}catch(Exception ex){
			LOGGER.error("", ex);
		}
		
		Object res = null;
		
		try{
			res = pjp.proceed();
		}catch(Exception ex){
			if(pathAndMsgOnError!=null){
				if(redirectAttributes!=null){
					redirectAttributes.addFlashAttribute(pathAndMsgOnError.errorMsgField(), ex.getMessage());
				}
				
				request.setAttribute(pathAndMsgOnError.errorMsgField(), ex.getMessage());
				return pathAndMsgOnError.path();
			}
			if(responseBody!=null){
				Result result = new Result();
				result.setStatus(ErrorConstant.OPERATION_ERROR.getErrorCode());
				result.setMessage(ex.getMessage());
				return result;
			}
			LOGGER.error("{}报错",request.getRequestURI(),ex);
		}
		try {
			
		} catch (Exception e) {
		}
		return res;
	}
}